<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use app\common\model\Brand as BrandModel;
use app\common\model\DeviceCat as DeviceCatModel;
use app\common\model\DeviceType as DeviceTypeModel;
use app\common\model\Device as DeviceModel;
use app\common\model\DeviceTemplateRel as DeviceTemplateRelModel;

use think\Validate;
use think\facade\Log;

class FeeTemplate extends Common
{
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
    //软删除位
    protected $deleteTime = 'isdel';

    protected $rule =   [
        'name'              =>  'require|max:50',
        'cat_id'            =>  'require',
        'brand_id'          =>  'require',
        'fee_type'          =>  'require',
        'fee_name'          =>  'require',
        'money'             =>  'require|regex:/^[0-9]+(.[0-9]{1,2})?$/',
        'sort'              =>  'number',
    ];

    protected $msg  =   [
        'name.require'              =>  '请输入模板名称',
        'name.max'                  =>  '模板名最多不能超过50个字符',
        'cat_id.require'            =>  '请选择设备分类',
        'brand_id.require'          =>  '请选择设备品牌',
        'fee_type.require'          =>  '请选择费用类型',
        'fee_name.require'          =>  '请选择计费参数',
        'money'                     =>  '请输入一个合法的金额',
        'sort'                      =>  '排序必须是数字',
    ];

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }

    /**
     *  添加模板方法
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $validate = new Validate($this->rule, $this->msg);
        $result = ['status' => true, 'msg' => '保存成功', 'data' => ''];
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 判断是否存在相同的计费规则
            $info = $this->where(['cat_id'=>$data['cat_id'], 'brand_id'=>$data['brand_id'], 'fee_type'=>$data['fee_type'], 'fee_name'=>$data['fee_name'], 'money'=>$data['money']])->find();
            if($info){
                $result['status'] = false;
                $result['msg'] = '存在相同的计费规则';   
            } else {
                if (!$this->allowField(true)->save($data))
                {
                    $result['status'] = false;
                    $result['msg'] = '保存失败';
                } 
            }
        }
        return $result;
    }

    /**
     *  修改模板信息
     * User:tony
     * @param $data
     * @return array
     */
    public function saveData($data)
    {
        $validate = new Validate($this->rule, $this->msg);
        $result = ['status' => true, 'msg' => '保存成功', 'data' => ''];
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 判断是否存在相同的计费规则
            $info = $this->where(['cat_id'=>$data['cat_id'], 'brand_id'=>$data['brand_id'], 'fee_type'=>$data['fee_type'], 'fee_name'=>$data['fee_name'], 'money'=>$data['money']])->where('id','neq',$data['id'])->find();
            if($info){
                $result['status'] = false;
                $result['msg'] = '存在相同的计费规则';   
            } else {
                if (!$this->allowField(true)->save($data, ['id' => $data['id']])) {
                    $result['status'] = false;
                    $result['msg'] = '保存失败';
                }
            }
        }
        return $result;
    }

    /**
     *  table WHERE搜索
     * User:tony
     * @param $post
     * @return mixed
     */
    protected function tableWhere($post)
    {
        $where = [];
        if (isset($post['name']) && $post['name'] != "") {
            $where[] = ['name', 'like', '%' . $post['name'] . '%'];
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['sort ASC'];
        return $result;
    }

    protected function tableFormat($list)
    {
        foreach ($list as $key => $val) {
            $brandModel = new Brand();
            $deviceCatModel = new DeviceCat();
            $deviceTypeModel = new DeviceType();

            $list[$key]['cat_name'] = $deviceCatModel->getNameById($val['cat_id']);
            $list[$key]['brand_name'] = $brandModel->getNameById($val['brand_id']);
            $list[$key]['type_name'] = $deviceTypeModel->getNameById($val['type_id']);
            $list[$key]['ctime'] = date('Y-m-d H:i:s', $val['ctime']);
            $list[$key]['utime'] = date('Y-m-d H:i:s', $val['utime']);
        }
        return $list;
    }

    /**
     *
     * 获取设备参数
     * User:tony
     * @return array
     */
    public function getFeeTemplateOptions()
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
 
        $cat_id  = input('param.cat_id', '');               // 分类
        $brand_id  = input('param.brand_id', '');           // 品牌
        $type_id  = input('param.type_id', '');             // 场景
 
        if (!$cat_id || $cat_id == "") {
            $result['msg'] = '设备分类不能为空';
            return $result;
        }
        if (!$brand_id || $brand_id == "") {
            $result['msg'] = '设备品牌不能为空';
            return $result;
        }
        if (!$type_id || $type_id == "") {
            $result['msg'] = '设备场景不能为空';
            return $result;
        }

        $deviceCatModel = new DeviceCatModel();
        $brandModel = new BrandModel();
        $deviceTypeModel = new DeviceTypeModel();
        $cat_name = $deviceCatModel->getNameById($cat_id);
        $brand_name = $brandModel->getNameById($brand_id);
        $type_name = $deviceTypeModel->getNameById($type_id);
   
        $conf = [];
        // 获取设备参数
        $device = \org\Device::create($cat_name, $brand_name, $type_name, $conf);

        if($device) {
            return $device->getOptions();
        } else {
            $result['msg'] = '不支持的设备类型、品牌或使用场景';
        }
 
        return $result;
    }

    /**
     *
     * 获取设备参数
     * User:tony
     * @return array
     */
    public function getDeviceOptionsByParams($cat_id, $brand_id, $deviceId, $all = false)
    {
        // 获取设备信息
        $deviceModel = new DeviceModel();
        $deviceInfo = $deviceModel->where(['cat_id' => $cat_id, 'brand_id' => $brand_id, 'sub_id' => $deviceId])->find();

        if ($deviceInfo) {

            if ($deviceInfo['status'] == 2) {
                $result['msg'] = '设备已停用！';
                return $result;
            }

            $deviceCatModel = new DeviceCatModel();
            $brandModel = new BrandModel();
            $deviceTypeModel = new DeviceTypeModel();

            $cat_name = $deviceCatModel->getNameById($deviceInfo['cat_id']);
            $brand_name = $brandModel->getNameById($deviceInfo['brand_id']);
            $type_name = $deviceTypeModel->getNameById($deviceInfo['type_id']);

            $conf = [];
            // 获取设备参数
            $device = \org\Device::create($cat_name, $brand_name, $type_name, $conf);
            $options = $device->getOptions();

            if(!$all) {
                // 这里要剔除没有被设备启用的计费条件
                $deviceTemplateRel = new DeviceTemplateRelModel();
                $deviceTemplateList = $deviceTemplateRel->getDeviceTemplate($deviceInfo['id']);
    
                $feeValue = [];
                foreach ($options['data']['fee'][0]['value'] as $key => $val) {
                    $found = false;
                    foreach ($deviceTemplateList as $i => $j) {
                        if ($j['fee_name'] == $val['name']) {
                            $val['money'] = $j['money'];
                            $found = true;
                            break;
                        }
                        
                    }

                    if (!$found) {
                        unset($options['data']['fee'][0]['value'][$key]);
                    } else {
                        $feeValue[] = $val;
                    }
                }

                $options['data']['fee'][0]['value'] = $feeValue;
            }
            
            return $options;
        }

        $result['msg'] = '设备不存在！';
        return $result;
    }

    /**
     *
     * 获取设备参数
     * User:tony
     * @return array
     */
    public function getDeviceOptions()
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
 
        $cat_id  = input('param.cat_id', '');               // 分类
        $brand_id  = input('param.brand_id', '');           // 品牌
        $deviceId  = input('param.deviceId', '');           // 设备编号

        if (!$cat_id || $cat_id == "") {
            $result['msg'] = '设备分类不能为空';
            return $result;
        }
        if (!$brand_id || $brand_id == "") {
            $result['msg'] = '设备品牌不能为空';
            return $result;
        }
        if (!$deviceId || $deviceId == "") {
            $result['msg'] = '设备编号不能为空';
            return $result;
        }

        return $this->getDeviceOptionsByParams($cat_id, $brand_id, $deviceId);
    }

    /**
     *
     * 获取费用
     * User:tony
     * @return array
     */
    public function getMoney($cat_id, $brand_id, $device_Id, $fee_type, $fee_name)
    {
        $result = ['status' => false, 'msg' => '', 'data' => ''];
 
        // 获取设备信息
        $deviceModel = new DeviceModel();
        $deviceInfo = $deviceModel->where(['cat_id' => $cat_id, 'brand_id' => $brand_id, 'sub_id' => $device_Id])->find();
        
        if ( $deviceInfo )
        {
            $templateInfo = $this->alias('template')
                ->field('template.id, template.name, template.money')
                ->join(config('database.prefix') . 'device_template_rel rel', 'rel.template_id = template.id', 'left')
                ->where(['template.cat_id' => $cat_id, 'template.brand_id' => $brand_id, 'rel.device_id' => $deviceInfo['id'], 'template.fee_type' => $fee_type, 'template.fee_name' => $fee_name])->find();

            if (!$templateInfo) {
                $result['msg'] = '尚未配置计费模板，请联系管理员！';
                return $result;
            }

            $result['data'] = $templateInfo;
            $result['status'] = true;
            return $result;
        }
 
        $result['msg'] = '设备不存在！';
        return $result;
    }
}
